package com.lagou.resume.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.lagou.resume.util.SpringBootUtil;
import com.lagou.resume.util.ZookeeperUtil;
import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.List;

/**
 * Druid数据源配置
 * @autor yzh
 * @date 2020/4/6 12:45
 */
@Configuration
public class DruidDataSourceConfig {

    @Bean(name = "druidDataSource")
    public DataSource druid() throws SQLException {
        ZkClient zkClient = ZookeeperUtil.getZkClient();
        zkClient.setZkSerializer(new MyZkSerializer());
        if(!zkClient.exists(ZookeeperUtil.ROOT_PATH)) {
            zkClient.createPersistent(ZookeeperUtil.ROOT_PATH, "");
        }
        List<String> chidrenList = setDbConfig();
        for (int i = 0; i < chidrenList.size(); i++) {
            createDbConfigListen(chidrenList.get(i));
        }
        return saveOrUpdateDataSource("save");
    }

    /**
     * 设置数据库配置的方法:将数据库配置设置到zookeeper中
     */
    public static List<String> setDbConfig() {
        ZkClient zkClient = ZookeeperUtil.getZkClient();
        List<String> chidrenList = zkClient.getChildren(ZookeeperUtil.ROOT_PATH);
        if(chidrenList == null || chidrenList.size() == 0) {
            zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/driverClassName", "com.mysql.jdbc.Driver");
            zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/url", "jdbc:mysql://47.105.185.180:3306/sss?useUnicode=true&characterEncoding=utf8&useSSL=false");
            zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/username", "root");
            zkClient.createEphemeral(ZookeeperUtil.ROOT_PATH + "/password", "Ll12369.@!");
        }
        return zkClient.getChildren(ZookeeperUtil.ROOT_PATH);
    }

    /**
     * 创建数据库配置监听的方法
     */
    public static void createDbConfigListen(String path) {
        ZookeeperUtil.getZkClient().subscribeDataChanges(ZookeeperUtil.ROOT_PATH+"/"+path, new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {
                saveOrUpdateDataSource("update");
            }

            @Override
            public void handleDataDeleted(String s) throws Exception {
                System.out.println("ss");
            }
        });
    }

    /**
     * 动态新增或修改数据源的方法
     * @param type
     * @return
     * @throws SQLException
     */
    public static DruidDataSource saveOrUpdateDataSource(String type) throws SQLException {
        ZkClient zkClient = ZookeeperUtil.getZkClient();
        DruidDataSource druidDataSource = null;
        if(type.equals("save")) {
            druidDataSource = new DruidDataSource();
        } else {
            druidDataSource = (DruidDataSource)SpringBootUtil.getApplicationContext().getBean("druidDataSource");
            //释放连接
            druidDataSource.close();
            //初始化数据源
            druidDataSource.init();
        }
        druidDataSource.setDriverClassName(zkClient.readData(ZookeeperUtil.ROOT_PATH + "/driverClassName"));
        druidDataSource.setUrl(zkClient.readData(ZookeeperUtil.ROOT_PATH + "/url"));
        druidDataSource.setUsername(zkClient.readData(ZookeeperUtil.ROOT_PATH + "/username"));
        druidDataSource.setPassword(zkClient.readData(ZookeeperUtil.ROOT_PATH + "/password"));
        return druidDataSource;
    }

}